/**
 * 页面加载器
 * 使用与导航条相同的方式动态加载页面内容
 */
document.addEventListener('DOMContentLoaded', function() {
  // 获取当前页面路径
  const currentPath = window.location.pathname.split('/').pop() || 'index.html';
  
  // 初始化Alpine.js数据
  window.navigation = function() {
    return {
      currentPage: currentPath,
      
      // 加载页面
      loadPage(pagePath) {
        if (this.currentPage === pagePath) return;
        
        // 触发加载开始事件
        document.dispatchEvent(new Event('contentLoadStart'));
        
        // 更新当前页面
        this.currentPage = pagePath;
        
        // 更新浏览器历史记录
        window.history.pushState({ page: pagePath }, '', pagePath);
        
        // 获取内容容器
        const contentContainer = document.getElementById('page-content');
        if (!contentContainer) {
          console.error('找不到内容容器 #page-content');
          return;
        }
        
        // 创建include标签
        const includeElement = document.createElement('include');
        includeElement.setAttribute('src', pagePath);
        
        // 清空内容容器并添加include标签
        contentContainer.innerHTML = '';
        contentContainer.appendChild(includeElement);
        
        // 处理include标签
        processIncludes();
        
        // 触发加载结束事件
        setTimeout(() => {
          document.dispatchEvent(new Event('contentLoadEnd'));
        }, 100);
      },
      
      // 判断当前页面
      isActive(path) {
        return this.currentPage === path;
      },
      
      // 切换移动菜单
      toggleMobileMenu() {
        this.mobileMenuOpen = !this.mobileMenuOpen;
      },
      
      // 移动菜单状态
      mobileMenuOpen: false,
      
      // 暗黑模式
      darkMode: localStorage.getItem('darkMode') === 'true',
      
      // 切换暗黑模式
      toggleDarkMode() {
        this.darkMode = !this.darkMode;
        localStorage.setItem('darkMode', this.darkMode);
        
        if (this.darkMode) {
          document.documentElement.classList.add('dark');
        } else {
          document.documentElement.classList.remove('dark');
        }
      }
    };
  };
  
  // 处理所有include标签
  async function processIncludes() {
    const includes = document.getElementsByTagName('include');
    
    // 转换为数组以避免在迭代过程中修改集合
    for (const include of Array.from(includes)) {
      const src = include.getAttribute('src');
      if (!src) continue;
      
      try {
        // 使用fetch API加载内容
        const response = await fetch(src);
        
        if (!response.ok) {
          throw new Error(`HTTP错误: ${response.status}`);
        }
        
        const html = await response.text();
        
        // 提取页面内容
        const parser = new DOMParser();
        const doc = parser.parseFromString(html, 'text/html');
        const content = doc.getElementById('main-content');
        
        if (content) {
          // 创建一个临时容器
          const temp = document.createElement('div');
          temp.innerHTML = content.innerHTML;
          
          // 添加淡入效果
          temp.style.opacity = '0';
          temp.style.transition = 'opacity 0.3s ease-in-out';
          
          // 将include标签替换为加载的内容
          while (temp.firstChild) {
            include.parentNode.insertBefore(temp.firstChild, include);
          }
          
          // 移除include标签
          include.parentNode.removeChild(include);
          
          // 执行新加载内容中的脚本
          executeScripts(include.parentNode);
          
          // 触发淡入动画
          setTimeout(() => {
            Array.from(include.parentNode.children).forEach(child => {
              if (child.style) {
                child.style.opacity = '1';
              }
            });
          }, 50);
          
        } else {
          console.error(`无法在 ${src} 中找到 #main-content 元素`);
          include.innerHTML = `<!-- 加载失败: ${src} 中没有 #main-content -->`; 
        }
      } catch (error) {
        console.error(`加载失败: ${src}`, error);
        include.innerHTML = `<!-- 加载失败: ${src} -->`; 
      }
    }
  }
  
  // 执行脚本
  function executeScripts(container) {
    const scripts = container.getElementsByTagName('script');
    Array.from(scripts).forEach(oldScript => {
      const newScript = document.createElement('script');
      
      // 复制脚本属性
      Array.from(oldScript.attributes).forEach(attr => {
        newScript.setAttribute(attr.name, attr.value);
      });
      
      // 复制脚本内容
      newScript.textContent = oldScript.textContent;
      
      // 替换旧脚本
      oldScript.parentNode.replaceChild(newScript, oldScript);
    });
  }
  
  // 处理浏览器的前进/后退操作
  window.addEventListener('popstate', (event) => {
    if (event.state && event.state.page) {
      const navigation = Alpine.store('navigation');
      if (navigation) {
        navigation.loadPage(event.state.page);
      }
    }
  });
});